/**
 * VimL算法示例 - 斐波那契数列
 * 
 * 本示例展示了VimL中实现经典算法的方法，包括：
 * 1. 递归算法实现
 * 2. 循环算法实现  
 * 3. 性能对比分析
 * 
 * 编译和运行：
 * mkdir -p build && cd build
 * cmake .. && ninja
 * ./bin/fibonacci_algorithms_example
 * 
 * 作者：VimL虚拟机项目组
 * 日期：2025-09-27
 */

#include "viml/compiler.h"
#include "viml/vm.h"
#include <iostream>

using namespace viml;

void print_header(const std::string& title) {
    std::cout << "\n" << std::string(50, '=') << std::endl;
    std::cout << " " << title << std::endl;
    std::cout << std::string(50, '=') << std::endl;
}

int main() {
    try {
        Compiler compiler;
        VM vm;
        
        print_header("VimL斐波那契算法示例");
        
        // 递归实现
        std::string recursive_fib = R"(
function fibonacci_recursive(n)
    echo "计算递归:", n
    if n <= 1
        return n
    else
        return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
    endif
endfunction

echo "=== 递归算法测试 ==="
let result5 = fibonacci_recursive(5)
echo "fibonacci_recursive(5) =", result5
)";
        
        std::cout << "执行递归实现..." << std::endl;
        auto bytecode1 = compiler.compile(recursive_fib, "recursive.vim");
        vm.execute(bytecode1);
        
        // 循环实现
        compiler.reset();
        vm.reset();
        
        std::string iterative_fib = R"(
function fibonacci_iterative(n)
    echo "计算循环:", n
    if n <= 1
        return n
    endif
    
    let a = 0
    let b = 1
    let i = 2
    
    while i <= n
        let temp = a + b
        let a = b
        let b = temp
        let i = i + 1
    endwhile
    
    return b
endfunction

echo "=== 循环算法测试 ==="
let result10 = fibonacci_iterative(10)
echo "fibonacci_iterative(10) =", result10

let result15 = fibonacci_iterative(15)
echo "fibonacci_iterative(15) =", result15
)";
        
        std::cout << "\n执行循环实现..." << std::endl;
        auto bytecode2 = compiler.compile(iterative_fib, "iterative.vim");
        vm.execute(bytecode2);
        
        print_header("算法总结");
        
        std::cout << "✓ 递归算法：代码简洁，但性能较低" << std::endl;
        std::cout << "✓ 循环算法：性能高效，适合实际应用" << std::endl;
        std::cout << "✓ VimL支持多种算法实现方式" << std::endl;
        std::cout << "\n🎉 斐波那契算法示例完成！" << std::endl;
        
        return 0;
        
    } catch (const std::exception& e) {
        std::cout << "\n❌ 算法示例执行失败: " << e.what() << std::endl;
        return 1;
    }
}